package com.free.system.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.json.JSONUtil;
import com.free.common.core.constant.RedisNodeCacheConstants;
import com.free.common.core.constant.RedisSystemCacheConstants;
import com.free.common.core.web.domain.R;
import com.free.common.redis.configure.RedisConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.free.common.core.utils.poi.ExcelUtil;
import com.free.common.core.web.controller.BaseController;
import com.free.common.core.web.domain.AjaxResult;
import com.free.common.core.web.page.TableDataInfo;
import com.free.common.log.annotation.Log;
import com.free.common.log.enums.BusinessType;
import com.free.common.security.annotation.RequiresPermissions;
import com.free.common.security.utils.SecurityUtils;
import com.free.system.domain.SysConfig;
import com.free.system.service.ISysConfigService;

/**
 * 参数配置 信息操作处理
 *
 * @author free
 */
@RestController
@RequestMapping("/config")
@Slf4j
public class SysConfigController extends BaseController {
    @Autowired
    private ISysConfigService configService;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 获取参数配置列表
     */
    @RequiresPermissions("system:config:list")
    @GetMapping("/list")
    public TableDataInfo list(SysConfig config) {
        startPage();
        List<SysConfig> list = configService.selectConfigList(config);
        return getDataTable(list);
    }

    @Log(title = "参数管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:config:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysConfig config) {
        List<SysConfig> list = configService.selectConfigList(config);
        ExcelUtil<SysConfig> util = new ExcelUtil<SysConfig>(SysConfig.class);
        util.exportExcel(response, list, "参数数据");
    }

    /**
     * 根据参数编号获取详细信息
     */
    @GetMapping(value = "/{configId}")
    public AjaxResult getInfo(@PathVariable Long configId) {
        return success(configService.selectConfigById(configId));
    }

    /**
     * 根据参数键名查询参数值
     */
    @GetMapping(value = "/configKey/{configKey}")
    public AjaxResult getConfigKey(@PathVariable String configKey) {
        return success(configService.selectConfigByKey(configKey));
    }

    /**
     * 新增参数配置
     */
    @RequiresPermissions("system:config:add")
    @Log(title = "参数管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysConfig config) {
        if (!configService.checkConfigKeyUnique(config)) {
            return error("新增参数'" + config.getConfigName() + "'失败，参数键名已存在");
        }
        config.setCreateBy(SecurityUtils.getUsername());
        return toAjax(configService.insertConfig(config));
    }

    /**
     * 修改参数配置
     */
    @RequiresPermissions("system:config:edit")
    @Log(title = "参数管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysConfig config) {
        if (!configService.checkConfigKeyUnique(config)) {
            return error("修改参数'" + config.getConfigName() + "'失败，参数键名已存在");
        }
        config.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(configService.updateConfig(config));
    }

    /**
     * 删除参数配置
     */
    @RequiresPermissions("system:config:remove")
    @Log(title = "参数管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{configIds}")
    public AjaxResult remove(@PathVariable Long[] configIds) {
        configService.deleteConfigByIds(configIds);
        return success();
    }

    /**
     * 刷新参数缓存
     */
    @RequiresPermissions("system:config:remove")
    @Log(title = "参数管理", businessType = BusinessType.CLEAN)
    @DeleteMapping("/refreshCache")
    public AjaxResult refreshCache() {
        configService.resetConfigCache();
        return success();
    }

    @Log(title = "设置用户的cid", businessType = BusinessType.UPDATE)
    @GetMapping("/setPushCid")
    public R setPushCid(String cid) {
        Long userId = SecurityUtils.getUserId();
        log.info("用户：{},设置cid：{}",userId,cid);
        redisTemplate.opsForSet().add(RedisSystemCacheConstants.getPushUserCidSet(userId), cid);
        redisTemplate.opsForSet().add(RedisSystemCacheConstants.getPushCidUserSet(cid), userId);
        return R.ok(cid);
    }
    @GetMapping("/getPortalConfig")
    public R getPortalConfig() {
        return R.ok(JSONUtil.parseObj("{\n" +
                "        \"articleCount\": 1,\n" +
                "        \"categoryCount\": 1,\n" +
                "        \"tagCount\": 1,\n" +
                "        \"viewCount\": \"1\",\n" +
                "        \"siteConfig\": {\n" +
                "            \"id\": 1,\n" +
                "            \"userAvatar\": \"https://static.ttkwsd.top/config/7b6f25adc2b9627b8918176888bee3b5.png\",\n" +
                "            \"touristAvatar\": \"https://static.ttkwsd.top/config/0bca52afdb2b9998132355d716390c9f.png\",\n" +
                "            \"siteName\": \"Hello World\",\n" +
                "            \"siteAddress\": \"https://www.ttkwsd.top\",\n" +
                "            \"siteIntro\": \"网站介绍\",\n" +
                "            \"siteNotice\": \"后端基于SpringBoot开发，前端基于Vue3 Ts Navie UI开发，<a href=\\\"https://gitee.com/wu_shengdong/blog\\\" style=\\\"color: #49b1f5;\\\">网站源码</a>\",\n" +
                "            \"createSiteTime\": \"2022-08-25\",\n" +
                "            \"recordNumber\": \"赣ICP备2022007910号\",\n" +
                "            \"authorAvatar\": \"https://static.ttkwsd.top/config/05409c1ed50047535f28a40464f7b1ab.jpg\",\n" +
                "            \"siteAuthor\": \"阿冬\",\n" +
                "            \"articleCover\": \"https://static.ttkwsd.top/config/d6a00d059a1e9729e763469deb4870df.jpg\",\n" +
                "            \"aboutMe\": \"\uD83C\uDF40个人简介\\n\\n想进大厂的小白\\n\\n感谢大佬们的开源精神\uD83D\uDC96\",\n" +
                "            \"github\": \"https://github.com/ICAN1999\",\n" +
                "            \"gitee\": \"https://gitee.com/wu_shengdong\",\n" +
                "            \"bilibili\": \"https://space.bilibili.com/505715511\",\n" +
                "            \"qq\": \"1039591471\",\n" +
                "            \"commentCheck\": 0,\n" +
                "            \"messageCheck\": 0,\n" +
                "            \"isReward\": 1,\n" +
                "            \"weiXinCode\": \"https://static.ttkwsd.top/config/994a286571b002e93281899cb402bd15.png\",\n" +
                "            \"aliCode\": \"https://static.ttkwsd.top/config/f0be9dc73e230d8821179b9303a9ff49.jpg\",\n" +
                "            \"emailNotice\": 1,\n" +
                "            \"socialList\": \"qq\",\n" +
                "            \"loginList\": \",gitee,github\",\n" +
                "            \"isMusic\": 1,\n" +
                "            \"musicId\": \"483997084\",\n" +
                "            \"isChat\": 1,\n" +
                "            \"websocketUrl\": \"ws://localhost:8080/websocket\"\n" +
                "        }\n" +
                "    }"));
    }
}
